package com.lagou.homeworkzk.config;

import com.lagou.homeworkzk.model.DataSourceInfo;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;

public class DynamicDatasourceHolder {
    private static DataSourceInfo currentDataSourceInfo;
    private static DataSource currentDataSource;
    public static DataSource getDataSource(){
        return currentDataSource;
    }

    /*
    更新数据源信息
     */
    public static synchronized void setDatasource(DataSourceInfo dataSourceInfo){
        currentDataSourceInfo=dataSourceInfo;
        release();
        createDataSource();
    }

    /*
    释放上一个连接池
     */
    private static void release(){
        if(currentDataSource!=null){
            HikariDataSource ds=(HikariDataSource)currentDataSource;
            if(!ds.isClosed()){
                ds.close();
            }
        }
    }

    private static void createDataSource(){
        if(currentDataSourceInfo!=null){
            HikariConfig config = new HikariConfig();
            config.setDriverClassName(currentDataSourceInfo.getClassName());
            config.setJdbcUrl(currentDataSourceInfo.getUrl());
            config.setUsername(currentDataSourceInfo.getUserName());
            config.setPassword(currentDataSourceInfo.getPassword());
            currentDataSource=new HikariDataSource(config);
        }
    }
}
